local converter = require("ptest.converter")

local M = {}

-- 获取 macOS 剪贴板的内容
function M.get_clipboard_content()
	local handle = io.popen("pbpaste")
	local result = handle:read("*all")
	handle:close()
	return result
end

function M.getLineCount(str)
	local count = 0
	for _ in str:gmatch("[^\r\n]+") do
		count = count + 1
	end
	return count
end

function M.curl_to_http(curl_command)
	return converter.curl_to_http(curl_command)
	-- curl_command = string.gsub(curl_command, '"', '\\"')
	-- local handle = io.popen("echo " .. '"' .. curl_command .. '"' .. " | curlconverter - --language http")
	-- local result = handle:read("*all")
	-- handle:close()
	-- return result
end

-- 定义一个函数，当检测到粘贴时打印 "paste"
function M.on_paste()
	local line = vim.api.nvim_get_current_line()

	if line:match("^curl") then
		local clipboard_content = M.get_clipboard_content()
		-- 在粘贴后处理剪贴板内容
		vim.schedule(function()
			M.add_comment_to_pasted_lines(clipboard_content)
		end)
	end
end

-- 在当前缓冲区的粘贴内容前面添加 "#"
function M.add_comment_to_pasted_lines(clipboard_content)
	local line_count = M.getLineCount(clipboard_content)
	-- 获取光标的位置
	local cursor_pos = vim.api.nvim_win_get_cursor(0)

	-- 获取光标行之后插入的内容
	local pasted_lines = vim.api.nvim_buf_get_lines(0, cursor_pos[1] - 1, cursor_pos[1] - 1 + line_count, false)

	-- 为每一行添加 "#"
	for i = 1, #pasted_lines do
		pasted_lines[i] = "# " .. pasted_lines[i]
	end

	-- 将处理过的内容重新设置回缓冲区
	vim.api.nvim_buf_set_lines(0, cursor_pos[1] - 1, cursor_pos[1] - 1 + line_count, false, pasted_lines)
	-- 调用转换方法
	local req = converter.curl_to_http(clipboard_content)
	local lines = vim.split(req, "\n")
	local index = cursor_pos[1] + line_count
	table.insert(lines, 1, "")
	vim.api.nvim_buf_set_lines(0, index, index, false, lines)
end

-- 设置自动命令，监听粘贴事件和插入模式的Control + V事件
function M.setup()
	-- 普通模式下监听粘贴操作
	vim.api.nvim_create_autocmd("TextChanged", {
		pattern = "*.http",
		callback = function()
			if vim.fn.mode() == "n" and vim.v.event.regname == nil then
				M.on_paste()
			end
		end,
	})
end

return M
